package fr.uvsq.isty.bdh.hchess.gui.game;

import fr.uvsq.isty.bdh.hchess.engine.GameData;
import fr.uvsq.isty.bdh.hchess.engine.HumanPlayer;
import fr.uvsq.isty.bdh.hchess.gui.MainWindow;
import fr.uvsq.isty.bdh.hchess.gui.style.Style;
import fr.uvsq.isty.bdh.hchess.interfacing.GameEvent;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 * A JPanel containing other info and commands about the display such as 
 * the PromotionChoicePanel or the surrender button.
 * @author Rémi Dubois <RemiEric.Dubois@gmail.com>
 */
public class SecondaryDisplayContainer extends JPanel implements Observer {
    
    private Style style; /** Board style singleton */
    private JButton surrendButton;
    
    private PromotionChoicePanel promotionChoicePanel;
    
    private HumanPlayer currentPlayer;
    
    
    public SecondaryDisplayContainer(MainWindow mainWindow) {
        
        try {
            this.style = Style.getInstance();
        } catch (IOException ex) {
        }
        
        promotionChoicePanel = new PromotionChoicePanel(mainWindow.getGameData());
        
        //this.setLayout(new BorderLayout());
        
        createButtons();
        
        this.add(promotionChoicePanel);
    }
    
    /**
     * create the buttons that will be displayed, and connect them to the player.
     */
    private void createButtons() {
        surrendButton = new JButton("Surrend");
        
        this.add(surrendButton);
        
        connectButtons();
    }
    
    @Override
    public void paintComponent(Graphics g) {
        Image bg = style.getBGImage();
        
        g.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), this);
    }
    
    /**
     * @return the promotion choice panel 
     */
    public PromotionChoicePanel getPromotionChoicePanel() {
        return promotionChoicePanel;
    }
    
    /**
     * connect the surrend button to the current player.
     */
    private void connectButtons() {
        surrendButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    if(currentPlayer != null) {
                        if (currentPlayer.isBlackPlayer()) currentPlayer.sendEventToReferee(GameEvent.BLACK_SURRENDERED);
                        else currentPlayer.sendEventToReferee(GameEvent.WHITE_SURRENDERED);
                    }
                }
            });
    }

    public void update(Observable o, Object arg) {
        if(o instanceof GameData) {
            GameData gameData = (GameData) o;
            // Human player
            currentPlayer = gameData.getCurrentHumanPlayer();
        }
    }
}
